﻿using AbpOne.Domain.Configurations;
using AbpOne.Domain.Shared;
using Hangfire;
using Hangfire.Dashboard.BasicAuthorization;
using Hangfire.SQLite;
using Volo.Abp;
using Volo.Abp.BackgroundJobs.Hangfire;
using Volo.Abp.Modularity;

namespace AbpOne.BackgroundJobs {
    [DependsOn(
        typeof(AbpBackgroundJobsHangfireModule)
    )]
    public class AbpOneBackgroundJobsModule : AbpModule {
        public override void ConfigureServices(ServiceConfigurationContext context) {
            context.Services.AddHangfire(configuration => {
                configuration.UseStorage(
                    new SQLiteStorage(AppSettings.ConnectionStrings, new SQLiteStorageOptions {
                        SchemaName = $"{AbpOneConst.DbTablePrefix}hangfire"
                    })
                );
            });
        }

        public override void OnApplicationInitialization(ApplicationInitializationContext context) {
            var app = context.GetApplicationBuilder();

            app.UseHangfireServer();
            app.UseHangfireDashboard(
                options: new DashboardOptions {
                    Authorization = new[] {
                        new BasicAuthAuthorizationFilter(new BasicAuthAuthorizationFilterOptions {
                            RequireSsl = false,
                            SslRedirect = false,
                            LoginCaseSensitive = true,
                            Users = new[] {
                                new BasicAuthAuthorizationUser {
                                    Login = AppSettings.Hangfire.Login,
                                    PasswordClear = AppSettings.Hangfire.Password
                                }
                            }
                        })
                    }
                }, pathMatch: "/hangfire");

            var service = context.ServiceProvider;

            // 使用扩展方法调用定时任务
            service.UseHangfireTest();

            // 壁纸爬虫任务
            service.UseWallpaperJob();

            // 抓取热点新闻
            service.UseHotNewsJob();
        }
    }
}